package com.alibaba.nacos.example.spring.cloud.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.nacos.example.spring.cloud.dao.MenuTypeRepository;
import com.alibaba.nacos.example.spring.cloud.model.MenuType;
import com.alibaba.nacos.example.spring.cloud.service.MenuTypeService;

@Service
@RefreshScope
public class MenuTypeServiceImpl implements MenuTypeService{
	
	private static final Logger log = LoggerFactory.getLogger(MenuTypeServiceImpl.class);
	
	private final MenuTypeRepository menutypeRepository;
	
    private final RedisTemplate redisTemplate;
    
    @Value("${app.user.cache}")
    private boolean cache;
    
    @Autowired
    public MenuTypeServiceImpl(MenuTypeRepository menutypeRepository,RedisTemplate redisTemplate) {
        this.menutypeRepository = menutypeRepository;
        this.redisTemplate = redisTemplate;
    }
    
	@Override
	public MenuType findMenuTypeById(String menu_type_id) {
		log.info("cache: {}", cache);
        if (cache) {
            Object obj = redisTemplate.opsForValue().get(key(menu_type_id));
            if (obj != null) {
            	log.info("get user from cache,menu_type_id: {}", menu_type_id);
                return (MenuType)obj;
            }
        }
        MenuType menutype = menutypeRepository.findById(menu_type_id).orElse(null);
        if (menutype != null) {
            if (cache) {
            	log.info("set cache for user,menu_type_id: {}", menu_type_id);
                redisTemplate.opsForValue().set(key(menu_type_id), menutype);
            }
        }
        return menutype;
	}

	private Object key(String menu_type_id) {
		 return String.format("nacos-spring-cloud-config-multi-data-ids:menutype:%d",menu_type_id);
	}
}
